package com.shujia.flink.core;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

public class Demo4ProcTIme {
    public static void main(String[] args) throws Exception {
        //创建环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> wordsDS = env.socketTextStream("master", 8888);

        /**
         * 实时统计单词的数量，每隔5秒统计最近10单词的数量
         */

        DataStream<Tuple2<String, Integer>> kvDS = wordsDS
                .map(word -> Tuple2.of(word, 1), Types.TUPLE(Types.STRING, Types.INT));

        //安装单词分组
        KeyedStream<Tuple2<String, Integer>, String> kvByDS = kvDS.keyBy(kv -> kv.f0);

        //划分窗口，窗口大小为10秒，滑动时间为5秒
        WindowedStream<Tuple2<String, Integer>, String, TimeWindow> windowDS = kvByDS.
                window(SlidingProcessingTimeWindows.of(Time.seconds(10), Time.seconds(5)));

        //计算单词的数量
        DataStream<Tuple2<String, Integer>> countDS = windowDS.sum(1);

        countDS.print();

        env.execute();


    }
}
